<!-- views/admin/intellectualProperty.vue -->
<template>
    <!-- 搜索区域 -->
    <div class="app-container" >
      <el-row :gutter="20" style="width:1375px;">
        <el-col :span="20" :xs="24">
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" 
                  v-show="showSearch" label-width="73px">
                  
            <el-form-item label="成果名称" prop="nameKeyword">
              <el-input v-model="queryParams.nameKeyword" placeholder="请输入成果名称"
                        clearable style="width: 200px" @keyup.enter="handleQuery"/>
            </el-form-item>
  
            <el-form-item label="授权号" prop="numberKeyword">
              <el-input  v-model="queryParams.numberKeyword" placeholder="授权号"
                clearable  style="width: 200px" @keyup.enter="handleQuery"/>
            </el-form-item>
  
            <el-form-item label="类别" prop="categoryKeyword">
              <el-input  v-model="queryParams.intellectualCategory" placeholder="请输入类别"
                clearable  style="width: 200px" @keyup.enter="handleQuery"/>
              <!-- <el-select v-model="queryParams.intellectualCategory" placeholder="请选择类别" 
                clearable style="width: 200px">
                <el-option label="国内授权外观设计专利" value="国内授权外观设计专利"/>
                <el-option label="国内授权实用新型专利" value="国内授权实用新型专利"/>
                <el-option label="计算机软件著作权" value="计算机软件著作权"/>
                <el-option label="其他" value="其他"/>
              </el-select> -->
            </el-form-item>
  
            <el-form-item>
              <el-button type="primary" icon="Search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
  
          <!-- 操作按钮区域 -->
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" plain icon="Plus" size="mini" @click="handleAdd">新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="success" plain icon="EditPen" size="mini" :disabled="single"  @click="handleUpdate" >修改</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger" plain icon="Delete" size="mini" :disabled="multiple" @click="handleDelete">删除</el-button>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
  
      <!-- 数据表格 -->
      <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="intellectualId" label="序号" width="90" />
        <el-table-column prop="username" label="姓名" width="130"/>
        <el-table-column prop="intellectualAchievementName" label="成果名称" width="250" />
        <el-table-column prop="authorizationNumber" label="授权号" width="180" />
        <el-table-column prop="intellectualCategory" label="类别" width="200" />
        <el-table-column prop="intellectualScore" label="分值" width="100" />
        <el-table-column prop="intellectualNotes" label="备注" />
      </el-table>
  
      <!-- 新增对话框 -->
      <el-dialog :title="dialogTitle" v-model="dialogVisible" width="38%">
        <el-form ref="formRef" :model="formData" label-width="100px">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="姓名" prop="username" required>
                <el-input v-model="formData.username" placeholder="请输入姓名" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="成果名称" prop="intellectualAchievementName" required>
                <el-input v-model="formData.intellectualAchievementName" placeholder="请输入成果名称" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="授权号" prop="authorizationNumber" required>
                <el-input v-model="formData.authorizationNumber" placeholder="请输入授权号" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="类别" prop="intellectualCategory" required>
                <el-input v-model="formData.intellectualCategory" placeholder="请输入类别"/>
            </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="分值" prop="intellectualScore" required>
                <el-input-number v-model="formData.intellectualScore" :min="0" :step="1" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="intellectualNotes">
                <el-input v-model="formData.intellectualNotes" type="textarea" placeholder="请填写内容" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
  
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="handleSubmit">确 定</el-button>
          </span>
        </template>
      </el-dialog>
  
      <!-- 分页组件 -->
      <Pagination v-model="queryParams" :total="total" @change="handleChange" />
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, reactive } from 'vue';
  import { getUserIntellProList, addUserIntellPro, updateUserIntellPro } from "@/api/intellectualProperty";
  import { ElMessage, ElMessageBox } from 'element-plus';
  import Pagination from '@/components/Pagination/index.vue';
  
  const tableData = ref([]); // 初始化为响应式数组
  const total = ref(0);
  const selectedRow = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  
  // 查询参数
  const queryParams = ref({
    nameKeyword: '',
    numberKeyword: '',
    intellectualCategory: '',
    currentPage: 1,
    pageSize: 10,
  });
  
  // 对话框相关变量
  const dialogVisible = ref(false);
  const dialogTitle = ref('新增知识产权成果');
  const formData = reactive({
    intellectualId: null,
    username: '',
    intellectualAchievementName: '',
    authorizationNumber: '',
    intellectualCategory: '',
    intellectualScore: 0,
    intellectualNotes: ''
  });
  
  // 控制显示/隐藏搜索表单
  const showSearch = ref(true);
  
  // 查询方法
  async function handleQuery() {
    try {
      const response = await getUserIntellProList({
        nameKeyword: queryParams.value.nameKeyword,
        numberKeyword: queryParams.value.numberKeyword,
        intellectualCategory: queryParams.value.intellectualCategory,
        currentPage: queryParams.value.currentPage, // 分页从1开始
        pageSize: queryParams.value.pageSize
      });
      
      tableData.value = response.data; // 更新表格数据
      total.value = response.total; // 总条目数
      console.log('查询结果:', response.data);
    } catch (error) {
      console.error('查询失败:', error);
      ElMessage.error('数据加载失败');
    }
  }
  
  // 重置查询条件
  function resetQuery() {
    queryParams.value = {
      nameKeyword: '',
      numberKeyword: '',
      intellectualCategory: '',
      currentPage: 1,
      pageSize: 10
    };
    handleQuery(); // 重置后重新查询
  }
  
  // 显示新增对话框
  function handleAdd() {
    Object.assign(formData, {
      intellectualId: null,
      username: '',
      intellectualAchievementName: '',
      authorizationNumber: '',
      intellectualCategory: '',
      intellectualScore: 0,
      intellectualNotes: ''
    });
    dialogTitle.value = '新增知识产权'; 
    dialogVisible.value = true;
  }
  
// 提交表单到后端
async function handleSubmit() {
  try {

    if (formData.intellectualId) { // 如果存在id，则为修改操作
      const sendData = {
        intellectualId: formData.intellectualId,
  username: formData.username,
  intellectualAchievementName: formData.intellectualAchievementName,
  authorizationNumber: formData.authorizationNumber,
  intellectualCategory: formData.intellectualCategory,
  intellectualScore: formData.intellectualScore,
  intellectualNotes: formData.intellectualNotes

      };
      await updateUserIntellPro(sendData);
      ElMessage({
        message: '修改成功',
        type: 'success'
      });
    } else { // 否则为新增操作
      // const sendData = {
      //   username: formData.username,
      //   email: formData.email,
      //   sex: formData.sex,
      //   phone: formData.phone,
      //   address: formData.address,
      //   role: formData.role
      // };
      await addUserIntellPro(formData);
      ElMessage({
        message: '新增成功',
        type: 'success'
      });
    }

    dialogVisible.value = false; // 关闭对话框
    await handleQuery(); // 刷新列表以显示新添加/修改的记录
  } catch (error) {
    console.error('操作失败:', error);
    ElMessage.error('操作失败，请重试');
  }
}
  
  // 表格选择处理
  function handleSelectionChange(selection) {
    selectedRow.value = selection;
    single.value = selection.length !== 1;  // 修改按钮状态
    multiple.value = selection.length === 0; // 删除按钮状态
  }
  
  // 修改操作
  async function handleUpdate() {
    if (selectedRow.value.length !== 1) { 
      ElMessage.error('请选择且仅选择一条记录进行修改');
      return;
    }
    Object.assign(formData, selectedRow.value[0]);
    dialogTitle.value = '修改知识产权成果'; 
    dialogVisible.value = true;
  }
  
  // 删除操作
  async function handleDelete() {
    const selectedIds = selectedRow.value.map(row => row.intellectualId);
    if (selectedIds.length === 0) {
      ElMessage.error('请选择要删除的记录');
      return;
    }
  
    try {
      await ElMessageBox.confirm(
        `确认删除选中的${selectedIds.length}条知识产权成果吗？`, 
        '警告',
        { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
      );
  
      await delIntellectual(selectedIds); 
      ElMessage.success('删除成功');
      
      await handleQuery();
      selectedRow.value = []; // 清空选中状态
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error(`删除失败: ${error.response?.data?.message || error.message}`);
      }
    }
  }
  
  // 分页处理
  const handleChange = (newPage, newPageSize) => {
    queryParams.value.currentPage = newPage;
    queryParams.value.pageSize = newPageSize;
    handleQuery();
  };
  
  // 页面加载时自动查询一次
  onMounted(() => {
    handleQuery();
  });
  </script>
  
  <style scoped>
  .el-input__inner {
    margin-left: 2px;
  }
  :deep(.el-input--small .el-input__inner) {
  height: 30px;
  line-height: 30px;
}
:deep(.el-form-item__label) {
  text-align: right;
  vertical-align: middle;
  float: left;
  font-size: 14px;
  color: #606266;
  line-height: 40px;
  padding: 0 12px 0 0;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}
:deep(.el-form-item) {
  display: flex;
  align-items: center;
  margin-bottom: 18px;
}
.el-form--inline .el-form-item{
margin-right: 18px !important;
}
  </style>
  